<?php

namespace app\index\controller;

use app\common\facade\CategoryFacade;
use app\common\model\ArticleModel;
use app\common\model\KeywordsModel;
use app\common\model\SitemapModel;
use think\Db;

class IndexController extends BaseController
{
    public function index()
    {
        $this->seo();
        $this->assign('page_url', url('/', [], true, true));
        return $this->fetch();
    }

    public function search($keyword, $channel = '')
    {
        $keyword = strip_tags($keyword);
        $this->seo($keyword);

        $params = ['page' => $this->request->param('page', 1), 'keyword' => $keyword];
        if (!empty($channel)) {
            $params['category'] = $channel;
        }

        $lists = (new ArticleModel())->tagList($params);
        $lists->appends('keyword', $keyword);

        if (!empty($keyword)) {
            if (session('search_keyword') != $keyword) {
                session('search_keyword', $keyword);
                KeywordsModel::grow($keyword, 'global', !$lists->isEmpty());
            }
        }

        $this->assign('keyword', $keyword);
        $this->assign('lists', $lists->items());
        $this->assign('page', $lists->render());
        $this->assign('totalCount', $lists->total());
        $this->assign('totalPage', $lists->lastPage());
        return $this->fetch();
    }

    public function sitemap($page = '', $force = '')
    {
        if (strpos(request()->url(), '.htm') > 0) {
            $this->seo();
            $this->assign('categories', CategoryFacade::getTreedCategory());
            return $this->fetch();
        }

        $cachename = getSetting('sitemap_mode') . '-sitemap-' . $page;
        $xml = cache($cachename);
        if (empty($xml) || $force) {
            $sitemap = new SitemapModel();
            if (getSetting('sitemap_mode') == '1') {
                $sitemap->createAll();
            } elseif ($page === '') {
                $sitemap->createIndex();
            } else {
                $sitemap->create($page);
            }
            $xml = $sitemap->getXML();
            cache($cachename, $xml, 3600 * 24);
        }
        return xml($xml);
    }

    public function subscribe()
    {
        if ($this->request->isPost()) {
            $email = $this->request->post('email');
            $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
            if (!preg_match($pattern, $email, $matches)) {
                $this->error('请填写正确的邮箱格式');
            }
            list($title, $domain) = explode('@', $email);
            $exists = Db::name('subscribe')->where('email', $email)->find();
            if (empty($exists)) {
                Db::name('subscribe')->insert([
                    'title' => $title,
                    'email' => $email,
                    'is_subscribe' => 1,
                    'create_time' => time(),
                    'update_time' => time()
                ]);
            } elseif ($exists['is_subscribe'] == 0) {
                Db::name('subscribe')->where('email', $email)->update(['is_subscribe' => 1, 'update_time' => time()]);
            }
            $this->success('感谢您的订阅！');
        }
        $this->error('参数错误');
    }

    public function share()
    {
        $product_id = getSetting('share_product');

        //判断会员是否已购买
        if ($this->isLogin) {
            $hasBuy = Db::view('orderProduct', '*')
                ->view('order', '*', 'order.order_id=orderProduct.order_id', 'LEFT')
                ->where('orderProduct.product_id', $product_id)
                ->where('order.member_id', $this->userid)
                ->find();
            if (!empty($hasBuy)) {
                return redirect(url('index/product/index'));
            }
        }
        if ($product_id) {
            return redirect(url('index/product/view', ['id' => $product_id]));
        } else {
            return redirect(url('index/product/index'));
        }
    }

    public function notice($id)
    {
        $article = Db::name('notice')->find($id);
        $this->seo($article['title']);

        $this->assign('article', $article);
        return $this->fetch();
    }

    public function jssdk($url)
    {
        $this->success('', '', $this->getShareData($url));
    }
}
